package com.baiqian.doupo.tileentity;

import net.minecraft.block.BlockState;
import net.minecraft.fluid.Fluids;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SUpdateTileEntityPacket;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.Constants;

import javax.annotation.Nullable;

public class ZhuJiLingYeTileEntity extends TileEntity implements ITickableTileEntity {
    private int tick = 0;

    public ZhuJiLingYeTileEntity() {
        super(TileEntityTypeRegistry.zhu_ji_ling_ye_tileentity.get());
    }
    @Override
    public void tick() {
        if (world!=null&&!world.isRemote) {
            ++tick;
            if(tick==30*60*20)//半小时
                world.setBlockState(pos,Fluids.WATER.getDefaultState().getBlockState());
            world.notifyBlockUpdate(pos, getBlockState(), getBlockState(), Constants.BlockFlags.BLOCK_UPDATE);
        }
    }

    @Nullable
    @Override//服务端发送数据包用的方法
    public SUpdateTileEntityPacket getUpdatePacket() {
        return new SUpdateTileEntityPacket(pos, 1/*序列号值，可以随便填写*/, getUpdateTag());
    }

    @Override//客户端接受数据包的方法
    public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
        handleUpdateTag(world.getBlockState(pkt.getPos()), pkt.getNbtCompound());
    }

    //在区块刚被载入时被调用的方法:打包
    @Override
    public CompoundNBT getUpdateTag() {
        CompoundNBT compoundNBT = super.getUpdateTag();
        compoundNBT.putInt("tick", tick);
        return compoundNBT;
    }

    //在区块刚被载入时被调用的方法：解包
    @Override
    public void handleUpdateTag(BlockState state, CompoundNBT tag) {
        tick=tag.getInt("tick");
    }


    @Override
    public void read(BlockState state, CompoundNBT nbt) {
        super.read(state, nbt);
        handleUpdateTag(state,nbt);
    }

    @Override
    public CompoundNBT write(CompoundNBT compound) {
        super.write(compound);
        return getUpdateTag();
    }
}
